angular.module('memberList', ['ui.grid', 'ui.grid.selection', 'ui.select', 'ui.grid.pagination',
        'ui.grid.resizeColumns', 'ui.grid.moveColumns', 'toastr', 'common'])
    .controller('memberListController',
        ['$scope', '$http', 'toastr',
            function ($scope, $http, toastr) {
                $scope.filter = {
                    name: '',
                    username: '',
                    role: '',
                    team: '',
                    page: 1,
                    size: 10
                };
                var dataCopy = [];
                $scope.option = [];
                $scope.optionNoAll = [];
                $http.get('/user/mapping').success(function (options) {
                    $scope.option.push({id: "", value: "全部"});
                    [].push.apply($scope.option, options.roleKey);
                    [].push.apply($scope.optionNoAll, options.roleKey);
                });

                if (!!$.cookie("toast")) {
                    toastr.success($.cookie("toast"));
                    $.cookie("toast", "");
                }

                $scope.data = [];

                $scope.columnOptions = [
                    {
                        field: "un_id",
                        name: "用户编号",
                        enableColumnMenu: false,
                        width: 100,
                        cellTemplate: '<span class="grid-data">{{MODEL_COL_FIELD}}</span>'
                    },
                    {
                        field: "username",
                        name: "用户账号",
                        enableColumnMenu: false,
                        cellTemplate: '<span class="grid-data">{{MODEL_COL_FIELD}}</span>'
                    },
                    {
                        field: "u_name",
                        name: "用户姓名",
                        enableColumnMenu: false,
                        cellTemplate: '<span class="grid-data">{{MODEL_COL_FIELD}}</span>'
                    },
                    {
                        field: "email",
                        name: "邮箱",
                        enableColumnMenu: false,
                        cellTemplate: '<span class="grid-data">{{MODEL_COL_FIELD}}</span>'
                    },
                    {
                        field: "team",
                        name: "所属研发组",
                        enableColumnMenu: false,
                        cellTemplate: '<span class="grid-data">{{MODEL_COL_FIELD}}</span>'
                    },
                    {
                        field: "role",
                        name: "用户角色",
                        enableColumnMenu: false,
                        selectOptions: $scope.optionNoAll,
                        cellTemplate: '<ui-select ng-model="MODEL_COL_FIELD" on-select="col.colDef.onSelect(row)" append-to-body="true">' +
                        '<ui-select-match>{{ $select.selected.value }}</ui-select-match>' +
                        '<ui-select-choices repeat="item.id as item in col.colDef.selectOptions">' +
                        '<div>{{ item.value }}</div>' +
                        '</ui-select-choices>' +
                        '</ui-select>',
                        onSelect: function (row) {
                            var wrong = false;
                            dataCopy.forEach(function (e) {
                                if (e.u_id == row.entity.u_id) {
                                    if (e.role == 'manager' && row.entity.role != 'manager') {
                                        wrong = true;
                                        row.entity.role = 'manager';
                                        toastr.warning("不能更改研发组长角色");
                                    } else if (e.role != 'manager') {
                                        if (row.entity.role == 'manager') {
                                            wrong = true;
                                            row.entity.role = e.role;
                                            toastr.warning("请在\"研发组管理\"中指定研发组长");
                                        }
                                    }
                                }
                            });
                            !wrong && (row.dirty = true);
                        }
                    },
                    {
                        field: "u_id",
                        name: "编辑",
                        enableColumnMenu: false,
                        width: "50",
                        cellTemplate: '<a class="grid-option" href="/member/update/{{MODEL_COL_FIELD}}">' +
                        '<i class="fa fa-lg fa-edit"></i></a>'
                    },
                    {
                        field: "u_id",
                        name: "保存",
                        enableColumnMenu: false,
                        width: "50",
                        cellTemplate: '<a class="grid-option" href="javascript:void(0)" ng-click="col.colDef.saveChange(row)">' +
                        '<i class="fa fa-lg fa-save" style="color :#d50"></i></a>',
                        saveChange: function (row) {
                            if (row.dirty) {
                                row.dirty = false;
                                if (row.entity.role === 'admin') {
                                    toastr.warning("无法更改为管理员");
                                    queryData();
                                    return;
                                }
                                $http.post('/member/find', {id: row.entity.u_id}).success(function (data) {
                                    if (data[0].role === 'admin') {
                                        toastr.warning("无法更改管理员角色");
                                        row.entity.role = 'admin';
                                        return;
                                    }
                                    $http.post('/member/save', {
                                        role: row.entity.role,
                                        id: row.entity.u_id
                                    }).success(function (data) {
                                        if (data === 'success') {
                                            toastr.success('保存成功');
                                        } else {
                                            toastr.error(data.description);
                                        }
                                    }).error(function () {
                                        toastr.error('请检查网络连接');
                                    });
                                }).error(function () {
                                    toastr.error("请检查网络连接");
                                });
                            } else {
                                toastr.warning('未做任何改动');
                            }
                        }
                    }
                ];

                $scope.gridOption = {
                    enableVerticalScrollbar: 0,
                    enableColumnResizing: true,
                    enableSelectAll: true,
                    exporterOlderExcelCompatibility: true,
                    enablePaging: true,
                    paginationPageSizes: [10, 25, 50],
                    paginationPageSize: 10,
                    useExternalPagination: true,
                    paginationTemplate: '/views/gridPagination.html',
                    enableGridMenu: false,
                    enableRowSelection: true,
                    excessRows: 1000,
                    columnDefs: $scope.columnOptions,
                    data: $scope.data
                };

                $scope.gridOption.onRegisterApi = function (gridApi) {
                    $scope.gridApi = gridApi;
                    gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
                        $scope.filter.page = newPage;
                        $scope.filter.size = pageSize;
                        $scope.gridOption.paginationPageSize = pageSize;
                        queryData();
                    });
                };

                $scope.addMember = function () {
                    //window.location.href = '/member/add';
                    $(".modal-add").css('display', 'block');
                    $("#modal-c").css('z-index', '1000');
                    $("#modal-i").css('z-index', '1000');
                };

                $scope.deleteMember = function () {
                    if ($scope.gridApi.selection.getSelectedRows().length > 0) {
                        var deleteRows = [];
                        var valid = true;
                        $scope.gridApi.selection.getSelectedRows().forEach(function (e) {
                            if (e.role === 'admin') {
                                valid = false;
                                return;
                            }
                            deleteRows.push(e.u_id);
                        });
                        if (!valid) {
                            toastr.warning("不能删除管理员");
                            return;
                        }

                        $(".remove-mem").modal();
                        $("#ensure-remove").on("click", function () {
                            $(".remove-mem").modal('hide');
                            $http.post('/member/delete', {id: deleteRows}).success(function (result) {
                                if (result == "success") {
                                    queryData();
                                    toastr.success("批量删除成功!");
                                } else {
                                    toastr.error("删除失败!" + result.description);
                                }
                            }).error(function () {
                                    toastr.error("请检查网络连接");
                                }
                            );
                        });
                    } else {
                        toastr.warning("未选择任何一行");
                    }
                };

                $scope.reset = function () {
                    $scope.filter = {
                        name: '',
                        username: '',
                        role: '',
                        team: '',
                        page: 1,
                        size: 10
                    };
                    queryData();
                };

                $scope.search = function () {
                    queryData();
                };

                function queryData() {
                    $scope.filter.limit = ($scope.filter.page - 1) * $scope.filter.size;
                    $scope.filter.count = $scope.filter.limit + $scope.filter.size;
                    $http.post('/member/find', $scope.filter).success(function (data) {
                        var un_id = 0;
                        data.data.forEach(function (e) {
                            var obj = {};
                            $.extend(obj, e);
                            dataCopy.push(obj);
                            e.un_id = ++un_id + ($scope.filter.page-1) * $scope.filter.size;
                        });

                        $scope.gridOption.data = data.data;
                        $scope.gridOption.totalItems = data.total;
                        setTimeout(function () {
                            $(window).resize();
                        }, 100);
                        if (data.data.length == 0) {
                            toastr.success("未查询到数据!");
                        }
                    }).error(function () {
                        toastr.error("请检查网络连接");
                    });
                }

                queryData();

                $scope.importExcel = function () {
                    $(".batch-import").modal();
                };

                window.uploadFile = function (upload) {
                    if (/.*\.xlsx$/.test($("input[type='file']").val())) {
                        $("#fileReplace").val($("#file").val());
                        if (!!upload) {
                            $("#fileReplace").val("");
                            $.ajaxFileUpload({
                                url: '/member/upload',
                                type: 'post',
                                secureuri: false,
                                fileElementId: 'file',
                                dataType: 'text',
                                success: function (data) {
                                    if (data == 'success') {
                                        $(".batch-import").modal("hide");
                                        $.cookie("toast", "批量导入成功");
                                        window.location.href = window.location.href;
                                    } else {
                                        toastr.error("导入失败!" + data);
                                    }
                                },
                                error: function (data, status, e) {
                                    toastr.error("请检查网络连接")
                                }
                            });
                        }
                    } else {
                        toastr.warning("请选择Excel表格文件类型");
                    }
                }
            }
        ]);